import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// Configure NProgress
NProgress.configure({
  showSpinner: false,
  minimum: 0.2,
  easing: 'ease',
  speed: 500
})

// Route components (lazy loading)
const Layout = () => import('../components/Layout/index.vue')
const Dashboard = () => import('../views/Dashboard/index.vue')
const DeviceList = () => import('../views/Devices/index.vue')
const DeviceDetail = () => import('../views/device/DeviceDetail.vue')
const ChannelList = () => import('../views/channel/ChannelList.vue')
const ChannelDetail = () => import('../views/channel/ChannelDetail.vue')
const StreamingView = () => import('../views/streaming/StreamingView.vue')
const Discovery = () => import('../views/discovery/index.vue')
const Settings = () => import('../views/settings/index.vue')
const About = () => import('../views/about/index.vue')
const NotFound = () => import('../views/error/404.vue')

// Define routes
const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '仪表板',
          icon: 'Odometer',
          affix: true,
          keepAlive: true
        }
      },
      {
        path: 'discovery',
        name: 'Discovery',
        component: Discovery,
        meta: {
          title: '设备发现',
          icon: 'Search',
          keepAlive: false
        }
      },
      {
        path: 'devices',
        name: 'DeviceList',
        component: DeviceList,
        meta: {
          title: '设备管理',
          icon: 'Monitor',
          keepAlive: true
        }
      },
      {
        path: 'devices/:id',
        name: 'DeviceDetail',
        component: DeviceDetail,
        meta: {
          title: '设备详情',
          icon: 'Monitor',
          hidden: true,
          activeMenu: '/devices'
        }
      },
      {
        path: 'channels',
        name: 'ChannelList',
        component: ChannelList,
        meta: {
          title: '通道管理',
          icon: 'VideoCamera',
          keepAlive: true
        }
      },
      {
        path: 'channels/:id',
        name: 'ChannelDetail',
        component: ChannelDetail,
        meta: {
          title: '通道详情',
          icon: 'VideoCamera',
          hidden: true,
          activeMenu: '/channels'
        }
      },
      {
        path: 'streaming',
        name: 'StreamingView',
        component: StreamingView,
        meta: {
          title: '视频播放',
          icon: 'VideoPlay',
          keepAlive: false
        }
      },
      {
        path: 'streaming/:channelId',
        name: 'StreamingChannel',
        component: StreamingView,
        meta: {
          title: '视频播放',
          icon: 'VideoPlay',
          hidden: true,
          activeMenu: '/streaming'
        }
      },
      {
        path: 'ptz',
        name: 'PTZControl',
        component: () => import('../views/ptz/PTZControl.vue'),
        meta: {
          title: 'PTZ控制',
          icon: 'VideoCamera'
        }
      },
      {
        path: 'recording',
        name: 'RecordingManagement',
        component: () => import('../views/recording/RecordingManagement.vue'),
        meta: {
          title: '录像管理',
          icon: 'VideoPlay'
        }
      },
      {
        path: 'event',
        name: 'EventManagement',
        component: () => import('../views/event/EventManagement.vue'),
        meta: {
          title: '事件管理',
          icon: 'Bell'
        }
      },
      {
        path: 'batch',
        name: 'BatchOperations',
        component: () => import('../views/batch/BatchOperations.vue'),
        meta: {
          title: '批量操作',
          icon: 'Operation'
        }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: Settings,
        meta: {
          title: '系统设置',
          icon: 'Setting',
          keepAlive: true
        }
      },
      {
        path: 'device/extensions',
        name: 'DeviceExtensions',
        component: () => import('../views/device/DeviceExtensions.vue'),
        meta: {
          title: '设备扩展功能',
          icon: 'Setting'
        }
      },
      {
        path: 'about',
        name: 'About',
        component: About,
        meta: {
          title: '关于系统',
          icon: 'InfoFilled',
          keepAlive: true
        }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面不存在',
      hidden: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

// Create router instance
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// Global before guards
router.beforeEach(async (to, from, next) => {
  // Start progress bar
  NProgress.start()

  // Set page title
  if (to.meta.title) {
    document.title = `${to.meta.title} - ONVIF设备管理系统`
  }

  // Route validation
  if (to.matched.length === 0) {
    next('/404')
    return
  }

  // Parameter validation for detail pages
  if (to.name === 'DeviceDetail' || to.name === 'ChannelDetail') {
    const id = to.params.id
    if (!id || isNaN(Number(id))) {
      ElMessage.error('无效的ID参数')
      next('/404')
      return
    }
  }

  // Streaming channel validation
  if (to.name === 'StreamingChannel') {
    const channelId = to.params.channelId
    if (!channelId || isNaN(Number(channelId))) {
      ElMessage.error('无效的通道ID')
      next('/streaming')
      return
    }
  }

  next()
})

// Global after guards
router.afterEach((to, from) => {
  // Finish progress bar
  NProgress.done()

  // Log route change in development
  if (import.meta.env.DEV) {
    console.log(`🚀 Route changed: ${from.path} → ${to.path}`)
  }
})

// Error handling
router.onError(error => {
  console.error('Router error:', error)
  NProgress.done()
  ElMessage.error('页面加载失败，请刷新重试')
})

export default router

// Export routes for menu generation
export { routes }
